package net.hn.hnms.biz.process.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.hn.hnms.biz.process.domain.JobProcess;
import net.hn.hnms.biz.process.domain.vo.JobProcessVo;
import net.hn.hnms.biz.process.mapper.JobProcessMapper;
import net.hn.hnms.biz.process.service.JobProcessService;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.ServiceException;
import net.hn.hnms.sys.common.core.utils.tool.Func;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class JobProcessServiceImpl extends ServiceImpl<JobProcessMapper, JobProcess> implements JobProcessService {

    private final RemoteUserService remoteUserService;

    public JobProcessServiceImpl(RemoteUserService remoteUserService) {
        this.remoteUserService = remoteUserService;
    }


    @Override
    public int insert(JobProcess jobProcess) {
        Long l = baseMapper.selectCount(new LambdaQueryWrapper<JobProcess>().eq(JobProcess::getPositionName, jobProcess.getPositionName())
                .eq(JobProcess::getProcessName, jobProcess.getProcessName()));
        if (l > 0) {
            throw new ServiceException("岗位工序已存在");
        }
        return baseMapper.insert(jobProcess);
    }

    @Override
    public void deleteBatch(List<String> idList) {
        baseMapper.deleteBatchIds(idList);
    }

    @Override
    public void update(JobProcess jobProcess) {
        Long l = baseMapper.selectCount(new LambdaQueryWrapper<JobProcess>().eq(JobProcess::getPositionName, jobProcess.getPositionName())
                .eq(JobProcess::getProcessName, jobProcess.getProcessName())
                .ne(JobProcess::getId, jobProcess.getId()));
        if (l > 0) {
            throw new RuntimeException("岗位工序已存在");
        }
        baseMapper.updateById(jobProcess);
    }

    @Override
    public JobProcessVo selectDetailById(String id) {
        JobProcess jobProcess = baseMapper.selectById(id);
        if (jobProcess != null) {
            return new JobProcessVo(jobProcess.getId(), jobProcess.getPositionName(), jobProcess.getProcessName(), jobProcess.getRemark(), jobProcess.getMineCode(), jobProcess.getCompanyCode(), jobProcess.getCreateUserId(), getUserName(jobProcess.getCreateUserId()), jobProcess.getCreateTime());
        }
        throw new ServiceException("岗位工序不存在");
    }

    @Override
    public ResponsePage<JobProcessVo> selectPageList(JobProcessVo jobProcessVo, PageQuery pageQuery) {
        Page<JobProcess> page = baseMapper.selectPage(pageQuery.build(), buildQuery(jobProcessVo).orderByDesc(JobProcess::getPositionName)
                .orderByDesc(JobProcess::getCreateTime));
        List<JobProcess> list = new ArrayList<>(page.getRecords());
        List<JobProcessVo> shiftReportingVos = BeanUtil.copyToList(list, JobProcessVo.class);
        shiftReportingVos.forEach(item -> {
            item.setCreateUserName(getUserName(item.getCreateUserId()));
        });
        return new ResponsePage<>(shiftReportingVos, page.getTotal());
    }

    @Override
    public List<JobProcessVo> getList(JobProcessVo jobProcessVo) {
        List<JobProcess> jobProcesses = baseMapper.selectList(buildQuery(jobProcessVo).orderByDesc(JobProcess::getPositionName).orderByDesc(JobProcess::getCreateTime));
        List<JobProcessVo> shiftReportingVos = BeanUtil.copyToList(jobProcesses, JobProcessVo.class);
        shiftReportingVos.forEach(item -> {
            item.setCreateUserName(getUserName(item.getCreateUserId()));
        });
        return shiftReportingVos;
    }


    private String getUserName(String userId) {
        if (userId == null)
            return "";
        LoginUser loginUser = remoteUserService.getUserInfoById(Long.parseLong(userId));
        if (loginUser != null) {
            return loginUser.getUsername();
        }
        return userId;
    }

    /**
     * 构造查询条件
     *
     * @param req
     * @return LambdaQueryWrapper<ExecutionFootageOutput> 查询条件
     */
    private LambdaQueryWrapper<JobProcess> buildQuery(JobProcessVo req) {
        LambdaQueryWrapper<JobProcess> lqw = new LambdaQueryWrapper<JobProcess>()
                .eq(Func.isNotEmpty(req.getPositionName()), JobProcess::getPositionName, req.getPositionName())
                .like(Func.isNotEmpty(req.getProcessName()) , JobProcess::getProcessName, req.getProcessName())
                .and(o -> o.eq(req.getMineCode() != null, JobProcess::getMineCode, req.getMineCode())
                        .or()
                        .eq(req.getCompanyCode() != null, JobProcess::getCompanyCode, req.getCompanyCode())
                );
        return lqw;
    }

}
